package com.jinzhi.jzcultivate.controller;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.itextpdf.text.pdf.PdfReader;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.config.IFastConfig;
import com.jinzhi.common.utils.DateUtils;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzapi.training.pojo.CoursesAndTeacherVo;
import com.jinzhi.jzweb.domain.ChapterDO;
import com.jinzhi.jzweb.domain.ChapterItemBankDO;
import com.jinzhi.jzweb.domain.TrainingResourcesDO;
import com.jinzhi.jzweb.pojo.entity.ChapterDocument;
import com.jinzhi.jzweb.pojo.request.ChapterRequest;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.utils.ValuesUtil;
import com.jinzhi.oss.service.OssService;
import com.jinzhi.oss.utils.MinioUtil;
import com.jinzhi.sys.service.UserService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.imageio.ImageIO;
import javax.validation.constraints.NotNull;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.*;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.zip.GZIPInputStream;

@Slf4j
@Controller
@AllArgsConstructor
@RequestMapping("/couInfo")
public class CourseController extends BaseController {

    @Autowired
    private CoursesService coursesService;
    @Autowired
    private ChapterDocumentService chapterDocumentService;
    @Autowired
    private ChapterService chapterService;
    @Autowired
    private ChapterItemBankService chapterItemBankService;
    @Autowired
    private TrainingResourcesService trainingResourcesService;
    @Autowired
    private ClassesService classesService;
    @Autowired
    private CoursesClassService coursesClassService;
    @Autowired
    private UserService userService;

    @Autowired
    private DocumentConverter converter;  //用于转换

    @Autowired
    IFastConfig ifastConfig;
    @Autowired
    private OssService ossService;

    @Autowired
    private DiscussService discussService;
    @Autowired
    private PapersDeploymentService papersDeploymentService;
    @Autowired
    private StuClassService stuClassService;

    @Autowired
    private MinioUtil minioUtil;

    public Map fileToPdf(Long resourceID) {

        TrainingResourcesDO resourcesDO = trainingResourcesService.selectById(resourceID);

        Map map = new HashMap();
        boolean returnflag = false;
        String uploadPdfUrl = "";
        String imgBaseUrl = "";

        String[] str = resourcesDO.getFileRoute().split("/");
        String newfileName = str[str.length - 1];
        //去掉后缀
        String[] str2 = newfileName.split("\\.");
        String newfileName2 = str2[0];
        System.out.println("newfileNameUrl:" + newfileName2);

        String savePath = ValuesUtil.localUrl + "/upload/pdfFile/"; //pdf文件生成保存的路径
        //String basePath = "/upload/pdfFile/"; //pdf文件生成保存的路径
        String fileName = newfileName2 + "_pdf";
        String fileType = ".pdf"; //pdf文件后缀
        String newFileMix = savePath + fileName + fileType;
        int pagecount = 0;

        String oosfilePath = ""; //oss路径
        //String url1[]=fileNameUrl.split("upload");
        /*for(int a=0; a<str.length; a++){
            System.out.println("oosfilePath :"+str[a]);
        }*/

        oosfilePath = resourcesDO.getFileRoute().substring(0, resourcesDO.getFileRoute().length() - (fileName + fileType).length());
        System.out.println("oosfilePath :" + oosfilePath);

        String oosfilePath2 = ""; //oss路径
        if (str.length > 1) {
            oosfilePath2 = str[0] + "//" + str[2] + '/';
        }
        System.out.println("oosfilePath2 :" + oosfilePath2);

        //查询转换后的pdf文件是否存在，不存在则转换文件
        boolean fileIsExists = false;
        URL url = null;
        try {
            if (resourcesDO.getUploadPdfUrl() != null) {
                System.out.println("fileUploadPdfUrl:" + resourcesDO.getUploadPdfUrl());
                url = new URL(resourcesDO.getUploadPdfUrl());
                HttpURLConnection urlcon = (HttpURLConnection) url.openConnection();
                //message = urlcon.getHeaderField(0);
                //文件存在‘HTTP/1.1 200 OK’ 文件不存在 ‘HTTP/1.1 404 Not Found’
                Long TotalSize = Long.parseLong(urlcon.getHeaderField("Content-Length"));
                if (TotalSize > 0) {
                    fileIsExists = true;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        if (!fileIsExists) {//文件还没有转换

            File downloadFile = null;
            boolean flag = false;
            try {
                // 构造URL
                URL weburl = new URL(resourcesDO.getFileRoute());
                // 打开连接
                URLConnection con = weburl.openConnection();
                // 设置请求超时为5s
                con.setConnectTimeout(5 * 1000);
                // 输入流
                InputStream is = con.getInputStream();
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;
                // 输出的文件流
                File sf = new File(ValuesUtil.localUrl + "/upload/pdfFile/");
                if (!sf.exists()) {
                    sf.mkdirs();
                }
                downloadFile = new File(sf.getPath() + "\\" + newfileName);
                System.out.println("downloadFile:" + sf.getPath() + "\\" + newfileName);

                OutputStream os = new FileOutputStream(sf.getPath() + "\\" + newfileName);
                // 开始读取
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                // 完毕，关闭所有链接
                os.close();
                is.close();
                flag = true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (flag) {
                //需要转换的文件为 downloadFile
                try {
                    File convertFile = new File(newFileMix);//转换之后文件生成的地址
                    //文件转化
                    converter.convert(downloadFile).to(convertFile).execute();

                    PdfReader reader;
                    try {
                        reader = new PdfReader(newFileMix);
                        pagecount = reader.getNumberOfPages();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                    System.out.println();
                    System.out.println("-------------pagecount:" + pagecount);
                    System.out.println();

                    //删除下载的文件
                    if (downloadFile.isFile() && downloadFile.exists()) {
                        downloadFile.delete();
                        System.out.println("删除单个文件" + downloadFile.getName() + "成功！");
                    } else {
                        System.out.println("删除单个文件" + downloadFile.getName() + "失败！");
                    }


                    //上传文件到OSS
                     /* InputStream inputStream = new FileInputStream(convertFile);
                    MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), inputStream);*/
                    FileInputStream fileInputStream = new FileInputStream(convertFile);
                    MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), convertFile.getName(),
                            ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                    uploadPdfUrl = ossService.uploadFileOss(multipartFile);
                    System.out.println("uploadPdfUrl=" + uploadPdfUrl);


                    //pdf转换成图片
                    InputStream input = new FileInputStream(new File(newFileMix));

                    byte[] pdfByte = new byte[input.available()];
                    input.read(pdfByte);
                    File sf2 = new File(ValuesUtil.localUrl + "/upload/");
                    if (!sf2.exists()) {
                        sf2.mkdirs();
                    }

                    imgBaseUrl = this.toImageFromBytes(ValuesUtil.localUrl + "/upload/", fileName, pdfByte, "png", 0, -1);
                    if (!imgBaseUrl.equals("")) {
                        returnflag = true;
                        //删除转换之后的文件
                        if (convertFile.isFile() && convertFile.exists()) {
                            convertFile.delete();
                            System.out.println("删除单个文件" + convertFile.getName() + "成功！");
                        } else {
                            System.out.println("删除单个文件" + convertFile.getName() + "失败！");
                        }
                    }
                    if (returnflag) {
                        resourcesDO.setUploadPdfUrl(uploadPdfUrl);
                        resourcesDO.setImgBaseUrl(imgBaseUrl);
                        resourcesDO.setImgName(fileName);
                        boolean update = trainingResourcesService.updateById(resourcesDO);
                        if (update) {
                            System.out.println("更新资源路径成功！");
                        }
                        map.put("status", "1");
                        map.put("msg", "转换文件成功");
                        map.put("page_count", pagecount);
                        map.put("file_url", resourcesDO.getFileRoute());
                        map.put("file_name", fileName);
                        map.put("base_url", imgBaseUrl);
                    } else {
                        System.out.println("下载文件失败！");
                        map.put("status", "0");
                        map.put("msg", "下载文件失败！");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                System.out.println("下载文件失败！");
                map.put("status", "0");
                map.put("msg", "下载文件失败！");
            }
        } else {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd_hhmmss");
            String timeUrl = simpleDateFormat.format(new Date());

            File downloadFile = null;
            boolean flag = false;
            // 输出的文件流
            File sf = new File(ValuesUtil.localUrl + "/upload/pdfFile/" + timeUrl);
            if (!sf.exists()) {
                sf.mkdirs();
            }
            try {

                // 构造URL
                URL weburl = new URL(resourcesDO.getUploadPdfUrl());
                // 打开连接
                URLConnection con = weburl.openConnection();
                // 设置请求超时为5s
                con.setConnectTimeout(5 * 1000);
                // 输入流
                InputStream is = con.getInputStream();
                // 1K的数据缓冲
                byte[] bs = new byte[1024];
                // 读取到的数据长度
                int len;


                downloadFile = new File(sf.getPath() + "\\" + fileName + fileType);
                System.out.println("downloadFile:" + sf.getPath() + "\\" + fileName + fileType);

                OutputStream os = new FileOutputStream(sf.getPath() + "\\" + fileName + fileType);
                // 开始读取
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
                // 完毕，关闭所有链接
                os.close();
                is.close();
                flag = true;
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            if (flag) {
                PdfReader reader;
                try {
                    reader = new PdfReader(sf.getPath() + "\\" + fileName + fileType);
                    pagecount = reader.getNumberOfPages();
                } catch (IOException e) {
                    e.printStackTrace();
                }

                //删除下载的文件
                if (downloadFile.isFile() && downloadFile.exists()) {
                    downloadFile.delete();
                    System.out.println("删除单个文件" + downloadFile.getName() + "成功！");
                } else {
                    System.out.println("删除单个文件" + downloadFile.getName() + "失败！");
                }

                map.put("status", "1");
                map.put("msg", "转换文件成功");
                map.put("page_count", pagecount);
                map.put("file_url", resourcesDO.getFileRoute());
                map.put("file_name", resourcesDO.getImgName());
                map.put("base_url", resourcesDO.getImgBaseUrl());

            } else {
                System.out.println("下载文件失败！");
                map.put("status", "0");
                map.put("msg", "下载文件失败！");
            }
        }
        return map;
    }

    /**
     *
     * @param fileurl 文件url
     * @return
     */
    public Map fileUrlToPdf(String fileurl) throws Exception {

        Map mymap = new HashMap();
        String uploadPdfUrl = "";

        String[] str = fileurl.split("/");
        String newfileName = str[str.length - 1];
        //去掉后缀
        String[] str2 = newfileName.split("\\.");
        String newfileName2 = str2[0];
        System.out.println("newfileNameUrl:" + newfileName2);

        String savePath = File.separator+"data"+File.separator+"jinzhiFile"; //pdf文件生成保存的路径

        String fileName = newfileName2;
        String fileType = ".pdf"; //pdf文件后缀
        String newFileMix = savePath + File.separator+fileName + fileType;
        int pagecount = 0;

        //转换
        File downloadFile = null;
        boolean flag = false;
        //中文转换一下
            fileurl=fileurl.replace(newfileName2, URLEncoder.encode(newfileName2, "UTF-8")) ;
            // 构造URL
            URL weburl = new URL(fileurl);
            // 打开连接
            URLConnection con = weburl.openConnection();
            // 设置请求超时为5s
            con.setConnectTimeout(5 * 1000);
            // 输入流
            InputStream is = con.getInputStream();
            // 2K的数据缓冲
            byte[] bs = new byte[2048];
            // 读取到的数据长度
            int len;
            // 输出的文件流
            File sf = new File( File.separator+"data"+File.separator+"jinzhiFile");
            if (!sf.exists()) {
                sf.mkdirs();
            }
            downloadFile = new File(sf.getPath() + File.separator + newfileName);
            System.out.println("downloadFile:" + sf.getPath() +File.separator + newfileName);

            OutputStream os = new FileOutputStream(sf.getPath() + File.separator+ newfileName);
            // 开始读取
            while ((len = is.read(bs)) != -1) {
                os.write(bs, 0, len);
            }
            // 完毕，关闭所有链接
            os.close();
            is.close();
            flag = true;


        if (flag) {
            //需要转换的文件为 downloadFile

                File convertFile = new File(newFileMix);//转换之后文件生成的地址
                //文件转化
                converter.convert(downloadFile).to(convertFile).execute();
                //转第二次，第一次pptx出现乱码。第二次不会
                converter.convert(downloadFile).to(convertFile).execute();
                PdfReader reader;

                    reader = new PdfReader(newFileMix);
                    pagecount = reader.getNumberOfPages();
                    //关闭
                    reader.close();




                System.out.println("-------------pagecount:" + pagecount);

                //删除下载的文件
                if (downloadFile.isFile() && downloadFile.exists()) {
                    downloadFile.delete();
                    System.out.println("删除单个文件" + downloadFile.getName() + "成功！");
                } else {
                    System.out.println("删除单个文件" + downloadFile.getName() + "失败！");
                }


                FileInputStream fileInputStream = new FileInputStream(convertFile);
                MultipartFile multipartFile = new MockMultipartFile(convertFile.getName(), convertFile.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);

                //上传到 minio服务器
                String fileNames = DateUtils.format(new Date(), DateUtils.DATE_PATTERN_11) + "/" + multipartFile.getOriginalFilename();
                Result result= minioUtil.minioUpload(multipartFile, fileNames, null);
                uploadPdfUrl=result.getData().toString();
                //调接口
//                String path="http://10.3.0.64:9900/minio/uploadFile";
//                String  path= "http://192.168.1.108:9900/minio/uploadFile";
//                CloseableHttpClient httpclient = HttpClients.createDefault();
//                HttpPost httppost = new HttpPost(path);
//                //设置超时
//                httppost.setConfig(RequestConfig.custom().setConnectTimeout(200000).setSocketTimeout(200000).build());
//                //设置传递文件
//                HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", new FileBody(convertFile, ContentType.APPLICATION_OCTET_STREAM.toString())).setMode(HttpMultipartMode.RFC6532).build();
//                httppost.setEntity(reqEntity);
//                //发送请求
//                CloseableHttpResponse httpResponse = httpclient.execute(httppost);
//                //获取参数转json
//                JSONObject jsonObject=JSONObject.parseObject(EntityUtils.toString(httpResponse.getEntity(), "utf-8"));
//                //关闭请求
//                httpclient.close();
//                if(httpResponse!=null){
//                    httpResponse.close();
//                }
//                uploadPdfUrl=jsonObject.getString("data");
                System.out.println("uploadPdfUrl=" + uploadPdfUrl);
                mymap.put("status", "1");
                mymap.put("pdfUrl", uploadPdfUrl);
                //关闭
                fileInputStream.close();
                //删除转换的文件
                if (convertFile.isFile() && convertFile.exists()) {

                    convertFile.delete();
                    System.out.println("删除转换后的单个文件" + convertFile.getPath() + "成功！");
                } else {
                    System.out.println("删除转换后的单个文件" + convertFile.getPath() + "失败！");
                }

        } else {
            System.out.println("下载文件失败！");
            mymap.put("status", "0");
            mymap.put("msg", "文件下载失败");
        }
        return mymap;
    }

    /*
     * PDF转图片
     * @attention: 支持自主选择起始页和结束页
     * @date: 2021-06-8 10:41
     * @param: imgPath
     * 图片全路径
     * @param: imgNamePrefix
     * 图片名称前缀
     * @param: pdfBytes
     * PDF二进制流
     * @param: imgType
     * 图片类型
     * @param: pageStartIndex
     * 开始页：开始转换的页码（第1页，页码为0）
     * @param: pageEndIndex
     * 结束页：结束转换的页码（最后1页，页码为-1）
     * @return: boolean
     * 只有PDF文件所有页数转换成功才返回true
     */
    public String toImageFromBytes(String imgPath, @NotNull String imgNamePrefix, byte[] pdfBytes, String imgType, int pageStartIndex, int pageEndIndex) {
        String baseUrl = "";
        System.out.println("toImageFromBytes:" + imgPath + "  " + imgNamePrefix);
        // 图片名称处理（注意文件名里不要有点，否则一律视为后缀名被抹掉）
        if (imgNamePrefix.indexOf(".") > 0) imgNamePrefix = imgNamePrefix.substring(0, imgNamePrefix.indexOf("."));

        // 添加路径分隔符
        // if (!imgPath.endsWith("/") && !imgPath.endsWith("\\")) imgPath += File.separator;

        try {
            // 加载PDF
            PDDocument doc = PDDocument.load(pdfBytes);
            PDFRenderer renderer = new PDFRenderer(doc);
            // pdf总页数
            int pageCount = doc.getNumberOfPages();
            System.out.println("该pdf文件共有" + pageCount + "页");
            for (int i = 0; i < pageCount; i++) {
                // dpi越大转换后越清晰，但转换速度越慢
                BufferedImage image = renderer.renderImageWithDPI(i, 250); // Windows native DPI
                // BufferedImage srcImage = resize(image, 240, 240);//产生缩略图
                File newImg;

                // 生成图片
                if (pageCount == 1)
                    newImg = new File(imgPath + imgNamePrefix + "_" + 1 + "." + imgType);
                else
                    newImg = new File(imgPath + imgNamePrefix + "_" + (i + 1) + "." + imgType);

                ImageIO.write(image, imgType, newImg);

                //上传文件到OSS
                FileInputStream fileInputStream = new FileInputStream(newImg);
                MultipartFile multipartFile = new MockMultipartFile(newImg.getName(), newImg.getName(),
                        ContentType.APPLICATION_OCTET_STREAM.toString(), fileInputStream);
                String uploadImgUrl = ossService.uploadFileOssNoPrefix(multipartFile);
                System.out.println("uploadImgUrl=" + uploadImgUrl);
                System.out.println("pdf第" + (i + 1) + "页转图片成功");


                if (i == 0) {
                    String fileName = imgNamePrefix + "_" + 1 + "." + imgType;
                    baseUrl = uploadImgUrl.substring(0, uploadImgUrl.length() - fileName.length());
                }

                //删除转换之后的文件
                if (newImg.isFile() && newImg.exists()) {
                    newImg.delete();
                    System.out.println("删除单个文件" + newImg.getName() + "成功！");
                } else {
                    System.out.println("删除单个文件" + newImg.getName() + "失败！");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("pdf-->;图片失败：" + e.getMessage());
        }

        System.out.println("pdf-->;图片成功");
        System.out.println("图片路径：" + baseUrl);
        return baseUrl;
    }

    @RequestMapping(value = "/documentConversion", method = RequestMethod.POST)
    @ResponseBody
    public Result documentConversion(String resourceId) {

        System.out.println("resourceId:" + resourceId);
        ChapterDocument chapterDocument = chapterDocumentService.selectById(resourceId);
        Map map = new HashMap();
        //获取数据看存不存在
        if (null==chapterDocument.getFilePdf()||chapterDocument.getFilePdf().trim().equals("")) {
            //转换保存
            Map oldmap = null;//转换文件为pdf文件
            try {
                oldmap = this.fileUrlToPdf(chapterDocument.getFile());
            } catch (Exception e) {
                log.error(e.getMessage());
            }
            if (null!=oldmap&&oldmap.get("status").toString().equals("1")) {
                //保存
                int number=chapterDocumentService.updatePdfById(resourceId,oldmap.get("pdfUrl").toString());
                System.out.println("加入数据库"+number);
                map.put("pdfUrl", oldmap.get("pdfUrl").toString());
            }else{
                map.put("msg",null!=oldmap?oldmap.get("msg").toString():"异常");
            }
        }else{
            map.put("pdfUrl", chapterDocument.getFilePdf());
        }
        Result r = new Result<>();
        r.setCode(200);
        r.setData(map);
        r.setMsg("获取成功！");
        return r;

    }

    @RequestMapping(value = "/addBrowseNum", method = RequestMethod.POST)
    @ResponseBody
    public Result addBrowseNum(String id) {
        //获取数据看存不存在
        System.out.println("resourceId:" + id);
        int number = coursesService.updateBrowseNumberById(id);
        Result r = new Result<>();
        r.setCode(200);
        r.setMsg("更新成功" + number);
        return r;

    }

    @RequestMapping(value = "/couInfo/view", method = RequestMethod.POST)
    @ResponseBody
    public Result couInfoView(String resourceId) {

        System.out.println("resourceId:" + resourceId);
        if (resourceId != null && !resourceId.equals("")) {
            TrainingResourcesDO resourcesDO = trainingResourcesService.selectById(Long.parseLong(resourceId));
            if (resourcesDO != null) {
                ChapterDO chapterDO = this.chapterService.selectById(resourcesDO.getChapterId());
                String[] str = resourcesDO.getFileRoute().split("/");
                String newfileName = str[str.length - 1];
                //获取后缀
                String[] str2 = newfileName.split("\\.");
                String extension = str2[str2.length - 1];
                System.out.println("extension:" + extension);
                System.out.println("resourcesDO." +
                        "getType():" + resourcesDO.getType());

                if (resourcesDO.getType() == 0 || resourcesDO.getType() == 2) {
                    if (extension.equals("doc") || extension.equals("docx") || extension.equals("txt") || extension.equals("ppt")
                            || extension.equals("pptx") || extension.equals("xls") || extension.equals("xlsx")
                    ) {
                        Map map = this.fileToPdf(resourcesDO.getId());//转换文件为pdf文件
                        if (map != null) {
                            if (map.get("status").toString().equals("1")) {
                                if (map.get("page_count") != null) {
                                    resourcesDO.setPageCount(Integer.valueOf(map.get("page_count") + ""));//文件页数
                                } else {
                                    resourcesDO.setPageCount(0);
                                }
                                if (map.get("file_url") != null) {
                                    resourcesDO.setFileRoute(map.get("file_url") + "");//pdf路径
                                    resourcesDO.setBaseUrl(map.get("base_url") + "");//访问文件路径，不包括文件名
                                    resourcesDO.setFileName(map.get("file_name") + "");//文件名
                                } else {
                                    resourcesDO.setFileRoute("");
                                    resourcesDO.setBaseUrl("");
                                    resourcesDO.setFileName("");
                                }
                                Result r = new Result<>();
                                r.setCode(200);
                                resourcesDO.setIsFree(chapterDO.getIsFree());
                                r.setData(resourcesDO);
                                r.setMsg("获取成功！");
                                return r;
                            } else {
                                Result r = new Result<>();
                                r.setCode(200);
                                resourcesDO.setIsFree(chapterDO.getIsFree());
                                r.setData(resourcesDO);
                                r.setMsg("获取成功！");
                                return r;
                            }
                        } else {
                            Result r = new Result<>();
                            r.setCode(200);
                            r.setData(resourcesDO);
                            resourcesDO.setIsFree(chapterDO.getIsFree());
                            r.setMsg("获取成功！");
                            return r;
                        }
                    } else {
                        Result r = new Result<>();
                        r.setCode(200);
                        resourcesDO.setPageCount(-1);
                        resourcesDO.setExtension("other");
                        r.setData(resourcesDO);
                        resourcesDO.setIsFree(chapterDO.getIsFree());
                        r.setMsg("获取成功！");
                        return r;
                    }
                } else if (resourcesDO.getType() == 4) {

                    resourcesDO.setBaseUrl("");
                    resourcesDO.setFileName("");
                    resourcesDO.setExtension(extension);
                    resourcesDO.setPageCount(1);
                    resourcesDO.setIsFree(chapterDO.getIsFree());

                    Result r = new Result<>();
                    r.setCode(200);
                    r.setData(resourcesDO);
                    r.setMsg("获取成功！");
                    return r;
                } else if (resourcesDO.getType() == 1 || resourcesDO.getType() == 5) {
                    Result r = new Result<>();
                    r.setCode(200);
                    Map mapVideo = new HashMap();
                    mapVideo.put("fileRoute", resourcesDO.getFileRoute());
                    mapVideo.put("name", resourcesDO.getName());
                    mapVideo.put("isFree", chapterDO.getIsFree());
                    mapVideo.put("introduce", chapterDO.getIntroduce());
                    mapVideo.put("minTime", chapterDO.getMinTime());
                    mapVideo.put("type", resourcesDO.getType());
                    r.setData(mapVideo);
                    r.setMsg("获取成功！");
                    return r;
                } else {
                    System.out.println("01");
                    Result r = new Result<>();
                    r.setCode(200);
                    r.setData(resourcesDO);
                    r.setMsg("获取成功！");
                    return r;
                }
            } else {
                System.out.println("02");
                Result r = new Result<>();
                r.setCode(-1);
                r.setData("");
                r.setMsg("该资源不存在！");
                return r;
            }
        } else {
            System.out.println("03");
            Result r = new Result<>();
            r.setCode(-1);
            r.setData("");
            r.setMsg("该资源不存在！");
            return r;
        }
    }

    /**
     * @param jsa
     * @param obj
     * @return
     */
    public JSONArray getAll(JSONArray jsa, JSONObject obj) {
        for (Object jsa1 : obj.getJSONArray("chapterDOS")) {
            JSONObject obj1 = (JSONObject) JSON.toJSON(jsa1);
            jsa.add(obj1);
            if (obj1.getJSONArray("chapterDOS") != null && obj1.getJSONArray("chapterDOS").size() > 0) {
                getAll(jsa, obj1);
            }
        }
        return jsa;
    }

    @Log("课程介绍")
    @GetMapping("/couInfo")
    String courseInfo(Model model, String id) {
        System.out.println("id=" + id);
        model.addAttribute("cou", coursesService.selectById(Long.parseLong(id)));
        //获取课程信息
        ChapterRequest request = new ChapterRequest();
        request.setType(1);
        request.setSize(1);
        request.setCoursesId(Long.parseLong(id));
        request.setIsDeleted(0);
        request.setPaging(1);
        request.setCurrent(1);
        Result result = chapterService.getChapter(request);
        Object myobj = null;
        JSONArray jsonArrayall = null;
        int one = 0, two = 0;
        if (result.getCode() == 0) {
            //获取到数据
            myobj = result.getData();
            //获取多少章，多少节
            try {
                JSONArray jsonArray = (JSONArray) JSON.toJSON(myobj);
                jsonArrayall = new JSONArray();
                for (Object j : jsonArray) {
                    one++;

                    JSONObject jsonObject = (JSONObject) JSON.toJSON(j);
                    JSONArray jsonArray1 = jsonObject.getJSONArray("chapterDOS");
                    for (Object oo : jsonArray1) {
                        if (!jsonArray1.contains(oo)) {
                            jsonArray1.add(oo);
                        }
                    }

                    jsonObject.put("chapterDOS", jsonArray1);

                    two += jsonArray1.size();

                    jsonArrayall.add(jsonObject);

                }
            } catch (Exception e) {
                //没有获取到数据/或者只有一条
                jsonArrayall = new JSONArray();
            }


        }
        model.addAttribute("myAllData", jsonArrayall);
        model.addAttribute("chapter", one);
        model.addAttribute("chapterDOS", two);
        model.addAttribute("fatherId", id);


        return "cultivateWeb/course/courseInfo";
    }

    @Log("课程介绍")
    @GetMapping("/couInfoChapterItems")
    ModelAndView couInfoChapterItems(Model model, String pid, String coursesId) {
        /*System.out.println("pid:"+pid);
        System.out.println("coursesId:"+coursesId);*/
        List<Map> map1Children = new ArrayList<>();
        if (StringUtils.isNotBlank(pid) && StringUtils.isNotBlank(coursesId)) {
            String key = coursesId + pid;

            List<ChapterDO> chapterDOS2 = (List<ChapterDO>) EhCacheUtil.get(key);

            if (chapterDOS2 == null) {
                chapterDOS2 = chapterService.findByKv("courses_id", Long.parseLong(coursesId), "parent_id", pid, "state", 0);
                EhCacheUtil.put(key, chapterDOS2);
            }

            if (chapterDOS2 != null && chapterDOS2.size() > 0) {
                for (ChapterDO chapterDO2 : chapterDOS2) {
                    Map map2 = new HashMap();
                    map2.put("id", chapterDO2.getId());

                    List<ChapterItemBankDO> chapterItemBankDOS2 = (List<ChapterItemBankDO>) EhCacheUtil.get(chapterDO2.getId() + "chapterDO2");
                    if (chapterItemBankDOS2 == null) {
                        chapterItemBankDOS2 = chapterItemBankService.findByKv("chapter_id", chapterDO2.getId(), "type", 0);
                        EhCacheUtil.put(chapterDO2.getId() + "chapterDO2", chapterItemBankDOS2);
                    }

                    if (chapterItemBankDOS2 != null && chapterItemBankDOS2.size() > 0) {
                        map2.put("isChaItem", "true");
                    } else {
                        map2.put("isChaItem", "false");
                    }
                    if (chapterDO2.getName() != null) {
                        map2.put("name", chapterDO2.getName());
                    } else {
                        map2.put("name", "");
                    }
                    map2.put("isFree", chapterDO2.getIsFree());//是否免费

                    map2.put("level", chapterDO2.getLevel());//层级


                    List<Map> map2Children = new ArrayList<>();

                    String key1 = coursesId + chapterDO2.getId();
                    List<ChapterDO> chapterDOS3 = (List<ChapterDO>) EhCacheUtil.get(key1);
                    if (chapterDOS3 == null) {
                        chapterDOS3 = chapterService.findByKv("courses_id", Long.parseLong(coursesId), "parent_id", chapterDO2.getId());
                        EhCacheUtil.put(key1, chapterDOS3);
                    }


                    if (chapterDOS3 != null && chapterDOS3.size() > 0) {
                        for (ChapterDO chapterDO3 : chapterDOS3) {
                            System.out.println("id:" + chapterDO3.getId());
                            Map map3 = new HashMap();
                            map3.put("id", chapterDO3.getId());

                            List<ChapterItemBankDO> chapterItemBankDOS3 = (List<ChapterItemBankDO>) EhCacheUtil.get(chapterDO3.getId() + "chapterItemBankDOS3");
                            if (chapterItemBankDOS3 == null) {
                                chapterItemBankDOS3 = chapterItemBankService.findByKv("chapter_id", chapterDO3.getId(), "type", 0);
                                EhCacheUtil.put(chapterDO3.getId() + "chapterItemBankDOS3", chapterItemBankDOS3);
                            }


                            if (chapterItemBankDOS3 != null && chapterItemBankDOS3.size() > 0) {
                                map3.put("isChaItem", "true");
                            } else {
                                map3.put("isChaItem", "false");
                            }
                            if (chapterDO3.getName() != null) {
                                map3.put("name", chapterDO3.getName());
                            } else {
                                map3.put("name", "");
                            }
                            map3.put("isFree", chapterDO3.getIsFree());//是否免费

                            map3.put("level", chapterDO3.getLevel());//层级


                            map2Children.add(map3);
                        }
                        map2.put("isHaveChildren", 1);
                        map2.put("children", map2Children);
                    } else {
                        map2.put("isHaveChildren", 0);
                        map2.put("children", "");
                    }
                    map1Children.add(map2);
                }

            }
        }

        if (map1Children.size() > 0) {
            model.addAttribute("isHaveChildren", 1);
        } else {
            model.addAttribute("isHaveChildren", 0);
        }

        // System.out.println("map1Children:"+map1Children.toString());
        model.addAttribute("selChapterItemsList", map1Children);

        ModelAndView mv = new ModelAndView();
        mv.setViewName("cultivateWeb/course/couInfoChapterItems");
        return mv;
    }

    @Log("课程介绍")
    @GetMapping("/couInfoChapterItems2")
    ModelAndView couInfoChapterItems2(Model model, String id, String coursesId) {
        /*System.out.println("id:"+id);
        System.out.println("coursesId:"+coursesId);*/
        model.addAttribute("chapter_id", id);
        List<TrainingResourcesDO> trainingResourcesDOS2 = trainingResourcesService.findByKv("courses_id", Long.parseLong(coursesId), "chapter_id", Long.parseLong(id));
        if (trainingResourcesDOS2 != null && trainingResourcesDOS2.size() > 0) {
            int i = 0;
            for (TrainingResourcesDO r : trainingResourcesDOS2) {
                r.setRindex(i);
                i++;
            }
        }
        model.addAttribute("resources", trainingResourcesDOS2);
        if (trainingResourcesDOS2.size() > 0) {
            model.addAttribute("isHaveResources", 1);
        } else {
            model.addAttribute("isHaveResources", 0);
        }


        ModelAndView mv = new ModelAndView();
        mv.setViewName("cultivateWeb/course/couInfoChapterItems2");
        return mv;
    }


    @Log("课程章节资源详情")
    @GetMapping("/couInfo/trainingResourcesDetails")
    String trainingResourcesDetails(Model model, String id, String resourceId, Integer rindex, String type, String t) {
        // System.out.println("id:"+id);

        String rIdCurrent = "";
        model.addAttribute("chapterId", id);


        ChapterDO chapterDO = (ChapterDO) EhCacheUtil.get(id + "chapterId");

        if (chapterDO == null) {
            chapterDO = chapterService.selectById(Long.valueOf(id));
            EhCacheUtil.put(id + "chapterId", chapterDO);
        }


        // System.out.println("id:"+chapterDO.getId());
        // System.out.println("getCoursesId:"+chapterDO.getCoursesId());

        if (type != null && type.equals("paper")) {

        } else {
            rIdCurrent = resourceId;
        }

        model.addAttribute("rIdCurrent", rIdCurrent);

        CoursesAndTeacherVo coursesAndTeacherVo = (CoursesAndTeacherVo) EhCacheUtil.get(chapterDO.getCoursesId() + "coursesAndTeacherVo");
        if (coursesAndTeacherVo == null) {
            coursesAndTeacherVo = coursesService.selCourseDetail(chapterDO.getCoursesId());
            EhCacheUtil.put(chapterDO.getCoursesId() + "coursesAndTeacherVo", coursesAndTeacherVo);
        }
        String key = chapterDO.getCoursesId() + chapterDO.getId().toString() + "chapterDO";
        List<TrainingResourcesDO> trainingResourcesDOS = (List<TrainingResourcesDO>) EhCacheUtil.get(key);
        if (rindex >= 1) {
            trainingResourcesDOS = null;
        }
        if (trainingResourcesDOS == null) {
            trainingResourcesDOS = trainingResourcesService.findByKv("courses_id", chapterDO.getCoursesId(), "chapter_id", chapterDO.getId());
            EhCacheUtil.put(key, trainingResourcesDOS);
        }

        model.addAttribute("rindexCurrent", rindex);
        if (trainingResourcesDOS != null && trainingResourcesDOS.size() > 0) {
            int i = 0;
            for (TrainingResourcesDO r : trainingResourcesDOS) {
                r.setRindex(i);
                i++;
            }
        }
        model.addAttribute("rTypeCurrent", trainingResourcesDOS.get(rindex).getType());
        model.addAttribute("rsize", trainingResourcesDOS.size());
        model.addAttribute("resources", trainingResourcesDOS);
        model.addAttribute("cou", coursesAndTeacherVo);

        model.addAttribute("chapterInfo", chapterDO);

        Long classId = 0L;
        List<Map> paperList = new ArrayList<>();

        model.addAttribute("paperList", paperList);

        return "cultivateWeb/course/trainingResourcesDetails";
    }

    @Log("课程搜索")
    @GetMapping("/courseSearch")
    String courseSearch(Model model, String name) {
        model.addAttribute("name", name);
        return "cultivateWeb/course/courseSearch";
    }

    @Log("课程订单确认页面")
    @GetMapping("/courseSurePay")
    String courseSurePay(Model model, String orderId, String courseId, String type) {
        model.addAttribute("orderId", orderId);
        model.addAttribute("type", type);
        model.addAttribute("courseId", courseId);
        return "cultivateWeb/course/courseSurePay";
    }

    @Log("课程支付页面")
    @GetMapping("/coursePay")
    String coursePay(Model model, String courseOrderId, String courseAmount, String courseId) {
        model.addAttribute("courseOrderId", courseOrderId);
        model.addAttribute("courseAmount", courseAmount);
        model.addAttribute("courseId", courseId);
        return "cultivateWeb/course/coursePay";
    }

    @Log("课程支付成功页面")
    @GetMapping("/coursePaySuccess")
    String coursePaySuccess(Model model, String courseOrderId, String courseId) {
        model.addAttribute("courseOrderId", courseOrderId);
        model.addAttribute("courseId", courseId);
        return "cultivateWeb/course/coursePaySuccess";
    }


    @Log("课程计划详情")
    @GetMapping("/coursePlan")
    String coursePlan(Model model, String id, String classId) {
        model.addAttribute("courseId", id);
        model.addAttribute("classId", classId);
        return "cultivateWeb/course/coursePlan";
    }

}
